#include "httputils.h"

void HttpUtils::writeResponse(QHttpResponse *resp, QString contentType, QByteArray &body)
{
    resp->setHeader("Content-Type", contentType);
    resp->setHeader("Content-Length", QString::number(body.size()));
    resp->writeHead(200);
    resp->end(body);
}

void HttpUtils::writeJsonResponse(QHttpResponse *resp, QString jsonString)
{
    QByteArray body = jsonString.toStdString().c_str();
    writeResponse(resp, QString::fromUtf8("application/json"), body);
}

void HttpUtils::responseError(QHttpResponse *resp, QString errorMessage)
{
    QString responseString = "{\"error\": \""+ errorMessage +"\"}";
    writeJsonResponse(resp, responseString);
}

int HttpUtils::findParamData(QString query, QString paramName)
{
    int idx = query.indexOf(paramName);

    if(idx==-1) return -1;

    idx += paramName.length();
    while(idx<query.length()) {
        QChar c = query.at(idx);
        if(!c.isSpace()) {
            if(c == '=') {
                return idx+1;
            } else {
                idx = query.indexOf(paramName,idx);
                if(idx==-1) {
                    return -1;
                }
                idx += paramName.length()-1;
            }
        }
        idx++;
    }

    return -1;
}

QString HttpUtils::extractGetParam(QString query, QString paramName)
{
    int dataPos = findParamData(query, paramName);
    int endPos=dataPos;

    if( (dataPos==-1) || (dataPos>=query.length()) ) {
        return QString();
    } else {
        while(endPos<query.length()) {
            if(query.at(endPos)=='&') {
                break;
            } else {
                endPos++;
            }
        }
        endPos--;
    }

    return query.mid(dataPos,(endPos+dataPos)+1);
}

